<template>
  <div class="partner-management">
    <div class="header">
      <h2>파트너 관리</h2>
      <div class="actions">
        <el-input v-model="search" placeholder="이름/추천코드/로그인ID/이메일/휴대폰번호 검색" clearable style="width: 280px" @keyup.enter.native="fetchPartners" />
        <el-select v-model="statusFilter" placeholder="상태" clearable style="width: 120px" @change="handleFilterChange">
          <el-option label="활성화" value="true" />
          <el-option label="비활성화" value="false" />
        </el-select>
        <el-button type="primary" @click="openCreate">새 파트너 추가</el-button>
      </div>
    </div>

    <el-table :data="partners" v-loading="loading" style="width: 100%">
      <el-table-column prop="referralCode" label="추천 코드" width="120">
        <template #default="{ row }">
          <el-tag type="info" effect="plain" class="mono">{{ row.referralCode }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="realName" label="실명" min-width="140" show-overflow-tooltip />
      <el-table-column prop="phoneNumber" label="휴대폰 번호" min-width="140">
        <template #default="{ row }">
          <span class="mono">{{ row.phoneNumber || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="로그인 ID" min-width="140" show-overflow-tooltip>
        <template #default="{ row }">{{ row.user?.loginId }}</template>
      </el-table-column>
      <el-table-column label="이메일" min-width="180" show-overflow-tooltip>
        <template #default="{ row }">{{ row.user?.email }}</template>
      </el-table-column>
      <el-table-column label="닉네임" min-width="140" show-overflow-tooltip>
        <template #default="{ row }">{{ row.user?.nickname || '-' }}</template>
      </el-table-column>
      <el-table-column prop="isActive" label="상태" width="100">
        <template #default="{ row }">
          <el-tag :type="row.isActive ? 'success' : 'info'">{{ row.isActive ? '활성화' : '비활성화' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="생성 시간" width="180">
        <template #default="{ row }">{{ formatDate(row.createdAt) }}</template>
      </el-table-column>
      <el-table-column label="작업" width="380" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="openEdit(row)">편집</el-button>
          <el-button size="small" type="warning" @click="openResetPassword(row)">비밀번호 재설정</el-button>
          <el-button size="small" :type="row.isActive ? 'danger' : 'success'" @click="toggleStatus(row)">{{ row.isActive ? '비활성화' : '활성화' }}</el-button>
          <el-button size="small" type="primary" @click="goReferrals(row)">하위 사용자</el-button>
          <el-button size="small" type="danger" @click="deletePartner(row)">삭제</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pager">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper"
        @current-change="fetchPartners"
      />
    </div>

    <!-- 추가/편집 팝업 -->
    <el-dialog v-model="showDialog" :title="editing ? '파트너 편집' : '파트너 추가'" width="560px">
      <el-form :model="form" :rules="rules" label-width="100px" ref="formRef">
        <el-form-item label="로그인 ID" prop="loginId" v-if="!editing">
          <el-input v-model="form.loginId" />
        </el-form-item>
        <el-form-item label="이메일" prop="email" v-if="!editing">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="비밀번호" prop="password" v-if="!editing">
          <el-input type="password" show-password v-model="form.password" />
        </el-form-item>
        <el-form-item label="실명" prop="realName">
          <el-input v-model="form.realName" />
        </el-form-item>
        <el-form-item label="휴대폰 번호" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" />
        </el-form-item>
        <el-form-item label="닉네임" prop="nickname">
          <el-input v-model="form.nickname" />
        </el-form-item>
        <el-form-item label="활성화">
          <el-switch v-model="form.isActive" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">취소</el-button>
        <el-button type="primary" :loading="saving" @click="save">{{ editing ? '저장' : '생성' }}</el-button>
      </template>
    </el-dialog>

    <!-- 비밀번호 재설정 팝업 -->
    <el-dialog v-model="showPwdDialog" title="비밀번호 재설정" width="460px">
      <el-form :model="pwdForm" :rules="pwdRules" label-width="100px" ref="pwdFormRef">
        <el-form-item label="새 비밀번호" prop="password">
          <el-input type="password" show-password v-model="pwdForm.password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirm">
          <el-input type="password" show-password v-model="pwdForm.confirm" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPwdDialog = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="submitReset">重置</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import request from '@/utils/request'

const router = useRouter()

const loading = ref(false)
const partners = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const search = ref('')
const statusFilter = ref('')

const showDialog = ref(false)
const editing = ref(false)
const saving = ref(false)
const formRef = ref<FormInstance>()
const pwdFormRef = ref<FormInstance>()
let currentId: string | null = null

const form = ref({ loginId: '', email: '', password: '', realName: '', phoneNumber: '', nickname: '', isActive: true })
const rules: FormRules = {
  loginId: [{ required: true, message: '请输入登录ID', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }, { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }, { min: 8, message: '至少8位', trigger: 'blur' }],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  phoneNumber: [{ required: true, message: '请输入手机号', trigger: 'blur' }, { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: ['blur', 'change'] }],
}

const showPwdDialog = ref(false)
const pwdForm = ref({ password: '', confirm: '' })
const pwdRules: FormRules = {
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }, { min: 8, message: '至少8位', trigger: 'blur' }],
  confirm: [{ required: true, message: '请再次输入密码', trigger: 'blur' }, { validator: (_r, v, cb) => { v !== pwdForm.value.password ? cb(new Error('两次输入不一致')) : cb() }, trigger: 'blur' }],
}

const fetchPartners = async () => {
  loading.value = true
  try {
    const params: any = {
      page: currentPage.value,
      limit: pageSize.value,
      search: search.value
    }
    // 只有当状态筛选有值时才添加status参数
    if (statusFilter.value) {
      params.status = statusFilter.value
    }
    const resp = await request.get('/api/admin/partners', { params })
    partners.value = resp.data.partners
    total.value = resp.data.total
  } catch (e) {
    ElMessage.error('获取合作伙伴失败')
  } finally {
    loading.value = false
  }
}

const openCreate = () => { editing.value = false; currentId = null; form.value = { loginId: '', email: '', password: '', realName: '', phoneNumber: '', nickname: '', isActive: true }; showDialog.value = true }
const openEdit = (row: any) => { editing.value = true; currentId = String(row.id); form.value = { loginId: row.user?.loginId || '', email: row.user?.email || '', password: '', realName: row.realName, phoneNumber: row.phoneNumber, nickname: row.user?.nickname || '', isActive: !!row.isActive }; showDialog.value = true }
const openResetPassword = (row: any) => { currentId = String(row.id); showPwdDialog.value = true; pwdForm.value = { password: '', confirm: '' } }

const save = async () => {
  saving.value = true
  try {
    if (editing.value && currentId) {
      await formRef.value?.validate()
      await request.put(`/api/admin/partners/${currentId}`, { realName: form.value.realName, phoneNumber: form.value.phoneNumber, nickname: form.value.nickname, isActive: form.value.isActive })
      ElMessage.success('保存成功')
    } else {
      await formRef.value?.validate()
      await request.post('/api/admin/partners', form.value)
      ElMessage.success('创建成功')
    }
    showDialog.value = false
    fetchPartners()
  } catch (e: any) {
    if (e?.message) ElMessage.error(e.message); else ElMessage.error(editing.value ? '保存失败' : '创建失败')
  } finally {
    saving.value = false
  }
}

const submitReset = async () => {
  if (!currentId) return
  saving.value = true
  try {
    await pwdFormRef.value?.validate()
    await request.put(`/api/admin/partners/${currentId}/password`, { password: pwdForm.value.password })
    ElMessage.success('密码已重置')
    showPwdDialog.value = false
  } catch (e) {
    ElMessage.error('重置失败')
  } finally {
    saving.value = false
  }
}

const toggleStatus = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要${row.isActive ? '禁用' : '启用'}该合作伙伴吗？`, '确认', { type: 'warning' })
    await request.put(`/api/admin/partners/${row.id}`, { isActive: !row.isActive })
    ElMessage.success(`${row.isActive ? '已禁用' : '已启用'}`)
    fetchPartners()
  } catch (e) {
    if (e !== 'cancel') ElMessage.error('操作失败')
  }
}

const goReferrals = (row: any) => {
  // 跳到会员管理，并带上 referrerId 过滤
  router.push({ path: '/members', query: { referrerId: row.user?.id, referrerName: row.realName } })
}


const formatDate = (s: string) => new Date(s).toLocaleString('zh-CN')
const handleFilterChange = () => { currentPage.value = 1; fetchPartners() }

// 删除合作伙伴
const deletePartner = async (partner: any) => {
  try {
    await ElMessageBox.confirm(
      `"${partner.realName}" 파트너를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.`,
      '파트너 삭제 확인',
      {
        confirmButtonText: '삭제',
        cancelButtonText: '취소',
        type: 'warning',
      }
    )

    const response = await request.delete(`/api/admin/partners/${partner.id}`)
    const result = response.data

    if (result.success) {
      ElMessage.success(result.message || '파트너가 삭제되었습니다')
      fetchPartners() // 목록 새로고침
    } else {
      ElMessage.error(result.error || '삭제 실패')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('삭제 중 오류가 발생했습니다')
    }
  }
}

onMounted(() => { fetchPartners() })
</script>

<style scoped>
.partner-management { padding: 20px; }
.header { display:flex; align-items:center; justify-content:space-between; margin-bottom:16px; }
.actions { display:flex; gap:10px; }
.mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace; }
.pager { display:flex; justify-content:center; padding: 16px 0; }
</style>
